<?php
namespace kernel\library;

class Config
{
    protected static $data = [];
    //载入配置文件
    public static function load(){
        $dir = BASICS_PATH.'config';
        $files = scandir($dir);
        foreach($files as $v){
            if(strpos($v, '.php')){
                $data = include_once  $dir.DIRECTORY_SEPARATOR.$v;
                if($data && is_array($data)){
                    $v = str_replace('.php', '', $v);
                    foreach ($data as $key => $val) {
                        if (is_array($val)) {
                            //初始化一下
                            self::$data[$v][$key] = [];
                            foreach($val as $k1 => $v1){
                                self::$data[$v][$key][$k1] = $v1;
                            }
                        } else {
                            self::$data[$v][$key] = $val;
                        }
                    }
                }
            }
        }
    }
    /**
     * @获取配置项
     * @param string $key
     * @param  $default
     * @return array|mixed|string
     */
    public static function get(string $key = '', $default = ''){
        
        if('' == $key){
            return self::$data;
        }else{
            $arr = explode('.', $key);
            if(isset(self::$data[$arr[0]])){
                if(isset($arr[1]) && isset(self::$data[$arr[0]][$arr[1]])){
                    if(isset($arr[2]) && isset(self::$data[$arr[0]][$arr[1]][$arr[2]])){
                        return self::$data[$arr[0]][$arr[1]][$arr[2]];
                    }else{
                        return self::$data[$arr[0]][$arr[1]];
                    }
                }else{
                    return self::$data[$arr[0]];
                }
            }
            return $default;
        }
        return $default;
    }
    /**
     * @设置config
     * @param string $key
     * @param  $val
     */
    public static function set($key, $val){
        $arr = explode('.', $key);
        if(isset($arr[0])){
            if(isset($arr[1])){
                if(isset($arr[2])){
                    self::$data[$arr[0]][$arr[1]][$arr[2]] = $val;
                }else{
                    self::$data[$arr[0]][$arr[1]] = $val;
                }
            }else{
                self::$data[$arr[0]] = $val;
            }
        }
    }
}

